package ro.gateway.aida.struts.action.listers;

import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import ro.gateway.aida.db.PersistenceManager;
import ro.gateway.aida.db.PersistenceToken;
import ro.gateway.aida.obj.Country;
import ro.gateway.aida.obj.Organization;
import ro.gateway.aida.obj.db.CountryDB;
import ro.gateway.aida.obj.db.OrganizationDB;
import ro.gateway.aida.struts.MultiTilesAction;
import ro.gateway.aida.struts.form.CountryFilterForm;
import ro.gateway.aida.usr.Arbiter;
import ro.gateway.aida.usr.Perms;
import ro.gateway.aida.usr.UserUtils;
import ro.gateway.aida.utils.LocalisedSortableList;
import ro.gateway.aida.utils.PageToken;
import ro.gateway.aida.utils.Utils;
import ro.xblue.translator.TranslatorUtils;


/*
 * Created on 08.01.2004
 * Local Projects Database
 * Mihai Postelnicu (mihai@ro-gateway.org)
 * (c) 2003 by eRomania Gateway
 */

/**
 * @author Mihai Postelnicu<p>
 *  administrator tool for listing all org objects. Country filtering is supported<br>
 *  CVS export is also available
 *  e-mail (mihai@ro-gateway.org)<br>
 * (c) 2003 by eRomania Gateway<p>
 */
public class ListOrgsAction extends MultiTilesAction {
    private OrganizationDB orgdb;
    private CountryDB cdb;
    private Arbiter ar;

    public ActionForward modeSelect(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        String mode = request.getParameter("mode");

        if (mode == null)
            mode = (String) request.getAttribute("mode");

        Utils.setBreadCrumbs(request, "bc.orgexp");

        if ("refresh".equals(mode))
            return modeRefresh(mapping, form, request, response);

        if ((mode != null) && mode.matches("[a-z]*Sort"))
            return modeSort(mapping, form, request, response);

        if (request.getParameter("csv_list") != null)
            return modeExport(mapping, form, request, response);

        if (request.getParameter("filter") != null)
            return modeFilter(mapping, form, request, response);

        return modeView(mapping, form, request, response);
    }

    public ActionForward modeFilter(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        CountryFilterForm cff = (CountryFilterForm) form;
        HttpSession session = request.getSession();
        String lang = TranslatorUtils.getCurrentLanguage(request, sc)
                                     .getLanguage();

        LocalisedSortableList sl = (LocalisedSortableList) session.getAttribute(LIST);

        //the filter
        sl = orgdb.getList();
        sl.setComparator(new Organization.LangComparator(lang));
        sl.setViewLang(lang);

        if (!cff.getIso3().equals("ALL")) {
            Iterator i = sl.iterator();

            while (i.hasNext()) {
                Organization o = (Organization) i.next();

                if ((o.getCountryISO3().equals(cff.getIso3())))
                    o.setSelected(true);
            }

            LocalisedSortableList sl2 = new LocalisedSortableList();
            i = sl.iterator();

            while (i.hasNext()) {
                Organization element = (Organization) i.next();

                if (element.isSelected())
                    sl2.add(element);
            }

            sl = sl2;
        }

        session.setAttribute(LIST, sl);
        sl.setViewLang(lang);
        PageToken.tokenizeList( request,  sc, sl, "orgs");
        
        return mapping.getInputForward();
    }

    public ActionForward modeExport(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        return mapping.findForward("csvexport");
    }

    public ActionForward modeSort(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        HttpSession session = request.getSession();
        LocalisedSortableList sl = (LocalisedSortableList) session.getAttribute(LIST);
        String lang = TranslatorUtils.getCurrentLanguage(request, sc)
                                     .getLanguage();
        String mode = request.getParameter("mode");

        if ("nameSort".equals(mode))
            sl.setComparator(new Organization.LangComparator(lang));

        if ("countrySort".equals(mode))
            sl.setComparator(new Organization.CountryComparator());

        if ("dateSort".equals(mode))
            sl.setComparator(new Organization.DateComparator());

        PageToken.tokenizeList( request,  sc, sl, "orgs");
        
        return mapping.getInputForward();
    }

    public ActionForward modeRefresh(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        HttpSession session = request.getSession();
        String lang = TranslatorUtils.getCurrentLanguage(request, sc)
                                     .getLanguage();

        session.setAttribute(LIST, orgdb.getList());

        LocalisedSortableList sl = (LocalisedSortableList) session.getAttribute(LIST);
        sl.setViewLang(lang);

        PageToken.tokenizeList( request,  sc, sl, "orgs");
        
        return mapping.getInputForward();
    }

    public ActionForward modeView(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        HttpSession session = request.getSession();

        LocalisedSortableList orgs = (LocalisedSortableList) session.getAttribute(LIST);
        
        PageToken.tokenizeList( request,  sc, orgs, "orgs");
        
        return mapping.getInputForward();
    }

    public ActionForward modePrepare(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        String lang = TranslatorUtils.getCurrentLanguage(request, sc)
                                     .getLanguage();
        PersistenceToken token = PersistenceManager.tokenLookup(sc);
        orgdb = OrganizationDB.getManager(token);
        ar = Arbiter.getManager(token);
        cdb = CountryDB.getManager(token);

        HttpSession session = request.getSession();

        if (session.getAttribute(Country.LIST) == null)
            session.setAttribute(Country.LIST, cdb.getCountries());

        if (UserUtils.getLogged(request, response) == null)
            return mapping.findForward("plslogin");

        if (!ar.canDo(request, Perms.ADMIN_TOOLS))
            return mapping.findForward("norights");

        LocalisedSortableList sl = (LocalisedSortableList) session.getAttribute(LIST);

        if (sl == null)
            request.setAttribute("mode", "refresh");
        else
            sl.setViewLang(lang);

        return modeSelect(mapping, form, request, response);
    }

    public static final String LIST = "adminOrg_LIST";
}
